import { RequestHandler } from "express"
import { container } from "tsyringe";
import { Body, Headers, Injector, NextFunction, Query, Request, Response } from "./tokens";
import { Router } from "./Router";


export const w7Api: RequestHandler = async (req, res, next) => {
    const now = Date.now();
    res.set('developer', '18639118753')
    const childContainer = container.createChildContainer()
    childContainer.register(Request, { useValue: req })
    childContainer.register(Response, { useValue: res })
    childContainer.register(NextFunction, { useValue: next })
    childContainer.register(Injector, { useValue: childContainer })
    childContainer.register(Body, { useValue: req.body })
    childContainer.register(Query, { useValue: req.query })
    childContainer.register(Headers, { useValue: req.headers })
    res.setTimeout(60 * 60 * 1000)
    res.on('close', () => {
        childContainer.dispose()
    })
    res.on('finish', () => {
        childContainer.dispose()
    })
    res.on('error', (err: Error) => {
        console.error(err)
    })
    const router = new Router(childContainer)
    Reflect.set(req, 'router', router)
    childContainer.register(Router, { useValue: router })
    try {
        const result = await router.load();
        if (typeof result === 'undefined') {
            if (res.headersSent) return;
            return next();
        }
        if (typeof result === 'object') {
            res.set('time', `${(Date.now() - now) / 1000}s`).json(result)
            return;
        }
        if (['string', 'number', 'boolean'].includes(typeof result)) {
            res.set('time', `${(Date.now() - now) / 1000}s`).send(`${result}`).end()
            return;
        }
    } catch (e) {
        return next(e)
    }
}